<template>
    <div>
        <el-row>
            <el-col :span="10">
                <div class="grid-content bg-purple">
                    <el-form :inline="true" :model="queryMap" class="demo-form-inline">
                        <el-form-item label="餐品名称">
                            <el-input v-model="queryMap.mealName" clearable></el-input>
                        </el-form-item>
                        <el-form-item>
                            <el-button type="primary" @click="search">查询</el-button>
                        </el-form-item>
                    </el-form>
                </div>
            </el-col>
            <el-col :span="6" :offset="8">
                <el-button-group>
                    <el-button icon="el-icon-plus" type="primary" @click="openAdd">新增</el-button>
                    <el-button icon="el-icon-edit" type="primary" @click="openEdit">修改</el-button>
                    <el-button icon="el-icon-delete" type="primary" @click="delMeal">删除</el-button>
                </el-button-group>
            </el-col>
        </el-row>
        <el-table
                :data="tableData"
                :height="530"
                border
                stripe
                style="width: 100%"
                @selection-change="handleSelectionChange"
        >
            >
            <el-table-column
                    prop="mealId"
                    type="selection"
            >

            </el-table-column>
            <el-table-column
                    label="序号"
                    type="index"
                    width="60"
                    align="center"
            >
            </el-table-column>
            <el-table-column
                    label="餐品名称"
                    prop="mealName"
                    width="180"
            >
            </el-table-column>
            <el-table-column
                    label="餐品单价"
                    prop="price"
                    width="180"
                    :formatter="formatPrice"
                    align="right"
            >
            </el-table-column>
            <el-table-column
                label="图片"
                prop="imageUrl"
                width="220"
                align="center">
                <template v-slot="scope">
                    <img :src="require('@/assets/images/'+scope.row.imageUrl)"  alt="aaa" style="width: 100px; height: 100px;">
                </template>
            </el-table-column>

        </el-table>
        <!-- 分页 -->
        <el-pagination
                :current-page="queryMap.page"
                :page-size="queryMap.limit"
                :page-sizes="[10, 20, 50, 100, 200]"
                :total="total"
                layout="total, sizes, prev, pager, next, jumper"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
        >
        </el-pagination>
        <!--餐品表单-->
        <MealForm
            :mealForm="mealForm"
            :formVisible.sync=formVisible
            :isEdit="isEdit"
            @submitForm="save"
        ></MealForm>
    </div>
</template>

<script>
import MealForm from "@/views/meal/MealForm.vue";
import DeptForm from "@/views/dept/DeptForm.vue";
export default {
    name: "MealView",
    components: {DeptForm, MealForm},
    data() {
        return {
            //查询条件
            queryMap: {
                page: 1,  // 当前页码
                limit: 10, // 每页条数
                mealName: '',//餐品名称
            },
            // 总条数
            total: 0,
            tableData: [],
            // 表单数据
            mealForm: {
                mealId: '',
                mealName: '',
                price:'',
                imageUrl: '',
            },
            // 新增表单显隐
            formVisible: false,
            //标志新增还是修改,false为新增
            isEdit: false,
            //复选框选中的数据
            multipleSelection: [],
        }
    },
    methods: {
        getImagePath(relativePath) {
            return `../../assets/${relativePath}`;
        },
        // 分页查询餐品信息
        getMealList() {
            const self = this
            this.$http.post('getMealByPage', this.queryMap).then(res => {
                self.tableData = res.data.meals
                self.total = res.data.count
            }).catch(() => {
                this.$message.error('获取餐品列表失败，请联系管理员')
            })
        },
        // 点击查询按钮
        search() {
            // 重置页面未第一页
            this.queryMap.page = 1;
            this.getMealList();
        },
        formatPrice(row, column, cellValue, index) {
            // 使用 toFixed 方法来格式化小数，保留两位小数
            // 注意：toFixed 返回的是一个字符串
            return cellValue.toFixed(2);
        },
        // 每页条数改变，val是改变后的每页条数
        handleSizeChange(val) {
            this.queryMap.limit = val;
            this.queryMap.page = 1;
            this.getDeptList();
        },
        // 页码改变，val是修改后的页面
        handleCurrentChange(val) {
            this.queryMap.page = val;
            this.getDeptList();
        },
        //点击复选框触发,val是勾选中的数据
        handleSelectionChange(val) {
            this.multipleSelection = val;
        },
        // 点击新增按钮
        openAdd() {
            this.isEdit = false
            // 重置表单
            this.mealForm= {
                mealId: '',
                mealName: '',
                price: '',
                imageUrl: '',
            }
            this.formVisible = true
        },
        //打开编辑页面
        openEdit(){
            const self = this
            //判断是否选中了一条数据,
            if (self.multipleSelection.length === 0) {
                self.$message({
                    type: 'warning',
                    message: "请选择要修改的数据"
                })
            } else if (self.multipleSelection.length > 1) {
                this.$message({
                    type: 'warning',
                    message: "只能选择一条数据"
                })
            } else {
                //获取选中行的主键
                let mealId = this.multipleSelection[0].mealId;
                this.$http.get("/getMealById/" + mealId).then(res => {
                    //根据主键获取要修改的数据
                    self.mealForm = res.data
                    self.isEdit = true
                    self.formVisible = true
                }).catch(error => {
                    self.$message.error("获取餐品对象失败")
                })
            }
        },
        //保存表单
        save(mealForm){
            mealForm.price = parseFloat(mealForm.price);
            if (!this.isEdit){
                this.$http.post("/addMeal",mealForm).then(res=>{
                    if (res.data ==='success'){
                        this.$message({
                            type:'success',
                            message:'保存成功'
                        })
                        //关闭弹框
                        this.formVisible = false
                        //刷新列表
                        this.queryMap.page=1;
                        this.getMealList();
                    }else {
                        this.$message.error("保存失败")
                    }
                }).catch(()=>{
                    this.$message.error("保存失败,请...")
                })
            }else {
                this.$http.post("editMeal",mealForm).then(res=>{
                    if (res.data ==='success'){
                        this.$message({
                            type:'success',
                            message:'修改成功'
                        })
                        //关闭弹框
                        this.formVisible = false
                        //刷新列表
                        this.queryMap.page=1;
                        this.getMealList();
                    }else {
                        this.$message.error("修改失败")
                    }
                }).catch(()=>{
                    this.$message.error("修改失败,请...")
                })
            }
        },
        //批量删除餐品
        delMeal(){
            const self = this
            //判断是否选中了一条数据,
            if(this.multipleSelection.length ===0){
                self.$message({
                    type:'info',
                    message:"请选择要删除的数据"
                })
                return
            }
            //询问用户
            this.$confirm('确定删除该餐品吗?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                //点击确认的回调
                //存放要删除的员工的主键
                let mealArr = [];
                for (let i = 0; i < self.multipleSelection.length; i++) {
                    mealArr.push(self.multipleSelection[i].mealId)
                }
                self.$http.post('delMeal',mealArr).then(res =>{
                    if (res.data==='success'){
                        self.$message({
                            type:"success",
                            message:"删除成功"
                        })
                        //刷新列表
                        self.queryMap.page=1;
                        self.getMealList()
                    }else {
                        self.$message.error("删除餐品失败,请重试")
                    }
                }).catch(()=>{
                    self.$message.error("删除员工失败,请重试")
                })
            }).catch(() => {
                //点击取消的回调
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });
            });
        },
    },
    created() {
        this.getMealList()
    }
}
</script>

<style scoped>

</style>